package com.vercon.moensmart.fragment

import android.graphics.Color
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import com.vercon.common.Constants
import com.vercon.common.utils.LogUtils
import com.vercon.moensmart.R
import com.vercon.moensmart.databinding.FragmentLightLayoutBinding
import com.vercon.moensmart.event.BaseEvent
import com.vercon.moensmart.fragment.base.BaseFragment
import com.vercon.moensmart.fragment.manager.FragmentOpenManager
import com.vercon.moensmart.mode.MenuStateBean
import com.vercon.moensmart.utils.LightHelper
import com.vercon.moensmart.utils.PreferenceUtils
import com.vercon.moensmart.view.shadow.ShadowConfig
import com.vercon.moensmart.view.shadow.ShadowHelper
import org.greenrobot.eventbus.EventBus

class LightFragment : BaseFragment<FragmentLightLayoutBinding?>() {

    companion object{
        val LIGHT_SWITCH_INIT_VALUE = 15 //15  亮度为0时，打开亮度开关的初始值
    }
    private var brightness = 0 //调节灯光亮度值
    private var colorData = 0 //调节色温
    private val isLight = true //是否有灯光，有灯光之后，分为，白灯，还有可以调色温的灯光
    private val isShow_color = true //是否显示色温
    private var isFirstSetLight = true //第一次打开软件时候，会设置灯光值，导致灯光按钮为true
    private var light_switch_state = false
    private val mHandler = Handler()
    private val delaytime = 160

    override fun onCreateViewBinding(inflater: LayoutInflater, parent: ViewGroup?): FragmentLightLayoutBinding {
        return FragmentLightLayoutBinding.inflate(inflater, parent, false)
    }

    override fun initData() {
        val config: ShadowConfig.Builder = ShadowConfig.Builder()
            .setColor(resources.getColor(R.color.black)) //View颜色
            .setShadowColor(Color.WHITE) //阴影颜色
            //.setGradientColorArray(mColor)//如果View是渐变色，则设置color数组
            .setRadius(46) //圆角
            .setOffsetX(0) //横向偏移
            .setOffsetY(0) //纵向偏移
        ShadowHelper.setShadowBgForView(binding?.colorLayout, config)
        ShadowHelper.setShadowBgForView(binding?.lightLayout, config)
    }

    override fun initListener() {
        //灯光开关
        binding?.igSwitch?.setOnClickListener(View.OnClickListener {
            binding?.igSwitch?.isSelected = !binding?.igSwitch?.isSelected!!
            saveDataState(binding?.igSwitch?.isSelected!!)
            changeUI()
            //homeMenuModel.setMenuLight(binding?.igSwitch?.isSelected())
            lightSwitchEvent()
            EventBus.getDefault().post(BaseEvent(Constants.refreshLight,binding?.igSwitch?.isSelected))
        })

        //灯光调节
        binding?.lightProgress?.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if(fromUser){
                    LogUtils.e("灯光progress=$progress")
                    binding?.tvLightValue?.setText("$progress%")
                    brightness = progress
                    if (progress > 0) {
                        val menuStateBean: MenuStateBean? = PreferenceUtils.getMenuState()
                        if(!binding?.igSwitch?.isSelected!! && menuStateBean?.light_switch == true){
                            EventBus.getDefault().post(BaseEvent(Constants.refreshLight,true))
                        }
                        if (!binding?.igSwitch?.isSelected()!! && !isFirstSetLight) {
                            light_switch_state = true
                            binding?.igSwitch?.setSelected(true)
                            changeUI()
                        }
                    } else {
                        if(binding?.igSwitch?.isSelected!!){
                            EventBus.getDefault().post(BaseEvent(Constants.refreshLight,false))
                        }
                        if (!isFirstSetLight) {
                            light_switch_state = false
                            binding?.igSwitch?.setSelected(false)
                            changeUI()
                        }
                    }
                    //homeMenuModel.setMenuLight(binding?.igSwitchisSelected())
                    controlLightByLight(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                //lastClickTime = 0;
                if (light_switch_state) {
                    controlLight()
                } else {
                    controlLightClose(false)
                }
            }
        })

        //色温调节
        binding?.temperatureProgress?.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                if(b){
                    val lastColorData = colorData
                    colorData = i
                    //避免进度条拖动太快，导致串口发送的数据未能及时响应,出现双色灯调节未完成
                    if (Math.abs(lastColorData - colorData) > 10) {
                        Thread {
                            try {
                                Thread.sleep(155)
                                if (!isFirstSetLight) {
                                    controlLight()
                                }
                            } catch (e: InterruptedException) {
                                e.printStackTrace()
                            }
                        }.start()
                    } else {
                        if (!isFirstSetLight) {
                            controlLight()
                        }
                    }
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                if (light_switch_state) {
                    LogUtils.e("colorProgress11")
                    controlLight()
                } else {
                    controlLightClose(false)
                }
            }
        })

        lightDataInit()


        binding?.igClose?.setOnClickListener { v ->
            activity?.let { FragmentOpenManager.getInstance().closeFragment(it) }
        }
        binding?.rlOutsideView?.setOnClickListener {
            activity?.let { FragmentOpenManager.getInstance().closeFragment(it) }
        }
    }

    private fun changeUI(){
        binding?.igLightState?.isSelected = binding?.igSwitch?.isSelected == true
        binding?.tvSwitchState?.text =  if (binding?.igSwitch?.isSelected == true) "ON" else "OFF"
    }

    private fun lightDataInit() {
        val menuStateBean: MenuStateBean? = PreferenceUtils.getMenuState()
        LogUtils.e("menuStateBean=$menuStateBean")
        brightness = menuStateBean!!.light_data
        colorData = menuStateBean.light_color
        binding?.igSwitch?.isSelected = menuStateBean.light_switch
        binding?.lightProgress?.progress = menuStateBean.light_data
        binding?.temperatureProgress?.progress = menuStateBean.light_color
        binding?.tvLightValue?.text = menuStateBean.light_data.toString() + "%"

        lightSwitchEvent()
        changeUI()
        mHandler.postDelayed(Runnable { isFirstSetLight = false }, (delaytime + 500).toLong())
    }


    private fun lightSwitchEvent() {
        light_switch_state = binding?.igSwitch?.isSelected!!
        if (!isFirstSetLight) { //是不是第一次打开设置开关
            //LightHelper.getInstance().againSend()
            if (light_switch_state) {
                setInitLightByLightSwitch()
                controlLight()
            } else {
                controlLightClose(false)
            }
        }
    }

    private fun controlLightByLight(progress: Int) {
        LogUtils.e("isFirstSetLight=$isFirstSetLight--progress=$progress")
        if (!isFirstSetLight) {
            if (progress > 0) {
                if (binding?.igSwitch?.isSelected == true) {
                    controlLight()
                }
            }
        } else {
            if (isLight) {
                //在色温时候设置第一次灯光数据
                controlLight()
            }
        }
    }

    /**
     * 灯光亮度为0的情况下，开灯，给予一个默认亮度
     */
    private fun setInitLightByLightSwitch() {
        if (brightness == 0) {
            brightness = LIGHT_SWITCH_INIT_VALUE
            binding?.lightProgress?.progress = brightness
        }
    }

    /**
     * 控制灯光
     */
    private fun controlLight() {
        LogUtils.e("light_switch_state=$light_switch_state")
        LightHelper.getInstance().controlLight(context, light_switch_state, isShow_color, brightness, colorData)
        saveDataState(false)
    }

    /**
     * 控制灯光关闭  light代表是不是app关闭后关灯 ,外面调用传true  ，里面使用传false
     */
    fun controlLightClose(light: Boolean) {
        LogUtils.e("controlLightClose")
        LightHelper.getInstance().controlLightClose(context, isShow_color)
        saveDataState(light)
    }

    private fun saveDataState(light: Boolean) {
        if (light) {
            light_switch_state = false //关闭app设置这个关闭
        }
        val bean = MenuStateBean(light_switch_state, brightness, colorData)
        LogUtils.e("save menuStateBean=$bean")
        PreferenceUtils.setData(PreferenceUtils.MenuState, bean)
    }


    override fun onClick(v: View?) {}
}